import axios from 'axios'

// 每次访问 CAS Server 生成不同的 JSESSIONID  开启后文件上传会有跨域问题
// axios.defaults.withCredentials = true
import qs from 'qs'

import { KToptips } from 'kbone-ui'

let showLoginMessageBox = false
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers['Access-Control-Allow-Origin'] = '*'
// 创建axios实例
const service = axios.create({
  baseURL: 'https://ting.yeyulingfeng.com', // api 的 base_url
  timeout: 15000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    const flag = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('application/json') !== -1
    if (!flag) {
      const mult = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('multipart/form-data') !== -1
      if (!mult) {
        config.data = config.data
      } else {
        config.data = qs.stringify(config.data)
      }
    }
    return config
  },
  error =>
  // Do something with request error
    Promise.reject(error)

)

// response 拦截器
service.interceptors.response.use(
  (response) => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (response.status === 200 && response.config.responseType === 'blob') { // 文件类型特殊处理
      return response
    } else if (res) {
      if (res.br === -1) {
        wx.showToast({
          title: '走丟了~',
          icon: 'error',
          mask: true,
          duration: 400
        })
        return Promise.reject('音乐资源丢失')
      }
      return res
    }
    return res
  },
  (error) => {
    const code = error.response.status
    if (code === 401) {
      if (!showLoginMessageBox) {
        showLoginMessageBox = true
        return false
      }
    } else if (code === 404) {
      wx.showToast({
        title: '404',
        icon: 'error',
        mask: true,
        duration: 1500
      })
    } else if (error.response.data.message && error.response.data.message.indexOf('友情提示;') > -1) {
      wx.showToast({
        title: '提示',
        icon: 'error',
        mask: true,
        duration: 1500
      })
    } else {
      wx.showToast({
        title: '500',
        icon: 'error',
        mask: true,
        duration: 1500
      })
    }
    return Promise.reject(error)
  }
)

export default service
